package cn.gcjxsc.controller.api.salesman;

import cn.gcjxsc.data.vo.salesman.BankCardVo;
import cn.gcjxsc.entity.member.Member;
import cn.gcjxsc.entity.salesman.BankCard;
import cn.gcjxsc.form.BankCardForm;
import cn.gcjxsc.service.integral.BankCardService;
import cn.gcjxsc.service.member.MemberService;
import com.zgxl.common.util.AjaxResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 业务员银行卡
 * @author pumbaa
 * @since 1.0
 */
@RestController("apiSalesmanBankCardController")
@RequestMapping("/api/salesman")
public class BankCardController {
    @Autowired
    private BankCardService bankCardService;
    @Autowired
    private MemberService memberService;

    /**
     * 查询指定的银行卡信息
     * @param id 银行卡id
     * @return
     */
    @RequestMapping("/bank/find/{id}")
    public BankCardVo findById(@PathVariable("id") Integer id) {
        BankCard bankCard = bankCardService.findById(id);
        if (null == bankCard) {
            return null;
        }
        return bankCardService.convert(bankCard);
    }

    /**
     * 查询指定会员的银行列表
     * @param memberId 会员id
     * @return
     */
    @RequestMapping("/bank/list")
    public List<BankCardVo> findByMemberId(@RequestParam("memberId") Integer memberId) {
        List<BankCard> list = bankCardService.findListByMemberId(memberId);
        List<BankCardVo> voList = new ArrayList<>();
        for (BankCard bankCard : list) {
            voList.add(bankCardService.convert(bankCard));
        }
        return voList;
    }

    /**
     * 添加银行
     * @param form 表单信息
     * @param bindingResult 检验结果
     * @return
     */
    @RequestMapping(value = "/bank/add", method = RequestMethod.POST)
    public AjaxResponse addBankCardNo(@Validated BankCardForm form, BindingResult bindingResult){
        if (bindingResult.getErrorCount() > 0) {
            return AjaxResponse.ajaxFailure(bindingResult.getFieldError().getDefaultMessage());
        }
        Integer memberId = form.getMemberId();
        Member member = memberService.findById(memberId);
        if (null == member) {
            return AjaxResponse.ajaxFailure("非法操作");
        }
        BankCard bankCard = bankCardService.newBankCard(form);
        try {
            bankCardService.saveBankCard(bankCard);
        } catch (Exception e) {
            return AjaxResponse.ajaxFailure("数据操作出错");
        }
        return AjaxResponse.ajaxSuccess();
    }
}
